package cc.taofoo.JUCTest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {


    public static void main(String[] args) throws InterruptedException {
        UnsafeCounter uc = new UnsafeCounter();
        // 线程池
        ExecutorService executorService = Executors.newCachedThreadPool();

        // CountDownLatch 可以在计数器归零后执行后续内容
        CountDownLatch cdl = new CountDownLatch(100);
        for(int i =0;i<100;i++){
            executorService.execute(()->{
                uc.add();
                cdl.countDown();
            });
        }
        cdl.await();
        System.out.println(uc.get());

    }
}
class UnsafeCounter {

    public  int count = 0;

    public synchronized void add() {
        count++;
    }

    public int get() {
        return count;
    }
}